<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button
            type="primary"
            plain
            class="el-icon-thumb"
            @click="showAddCateDialog"
            >添加分类</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格 -->
      <tree-table
        class="treeTable"
        :data="catelist"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        border
      >
        <!-- 是否有效 -->
        <template slot="isok" slot-scope="scope">
          <i
            style="color: lightgreen"
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
          ></i>
          <i style="color: red" class="el-icon-error" v-else></i>
        </template>
        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="success" size="mini" v-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag type="info" size="mini" v-if="scope.row.cat_level === 2"
            >三级</el-tag
          >
        </template>
        <!-- 操作 -->
        <template slot="opt" slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            plain
            size="mini"
            @click="showEditDialog(scope.row.cat_id)"
            >编辑</el-button
          >
          <el-button
            type="warning"
            icon="el-icon-delete"
            plain
            size="mini"
            @click="removeCateByID(scope.row.cat_id)"
            >删除</el-button
          >
        </template>
      </tree-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="querInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="querInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加分类的对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @close="addCateDialogClosed"
    >
      <!-- 添加分类对话框的内容 -->
      <el-form
        :model="addCateForm"
        :rules="addCateFormRules"
        ref="addCateFormRef"
        label-width="90px"
      >
        <el-form-item label="分类名称:" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类:">
          <!-- options:指定数据源 -->
          <!-- props:指定配置对象 -->
          <!-- v-model=""必须绑定数组 -->
          <!-- clearable:清空按钮 -->
          <!-- change-on-select：允许选择任意一级分类 -->
          <el-cascader
            clearable
            change-on-select
            :options="parentCateList"
            :props="cascaderProps"
            v-model="selectedKeys"
            @change="parentCateChanged"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户的对话框 -->
    <el-dialog
      title="修改分类"
      :visible.sync="editCateDialogVisible"
      width="50%"
      @close="editCateDialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="editCateRoleForm"
        :rules="editCateRoleFormRules"
        ref="editCateRoleFormRef"
        label-width="90px"
      >
        <el-form-item label="分类名称:" prop="cat_name">
          <el-input v-model="editCateRoleForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类:">
          <el-cascader clearable disabled></el-cascader>
        </el-form-item>
      </el-form>
      <!-- 底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Cate',
  data() {
    return {
      //查询条件
      querInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      //商品分类的数据列表，默认为空
      catelist: [],
      //总数据条数
      total: 0,
      //为table指定列的定义
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name',
        },
        {
          label: '是否有效',
          type: 'template', //使用模板列-作用域插槽
          template: 'isok', //当前列的模板名称
        },
        {
          label: '排序',
          type: 'template', //使用模板列-作用域插槽
          template: 'order', //当前列的模板名称
        },
        {
          label: '操作',
          type: 'template', //使用模板列-作用域插槽
          template: 'opt', //当前列的模板名称
        },
      ],
      //控制添加分类对话框的显示与隐藏
      addCateDialogVisible: false,
      //控制修改分类对话框的显示与隐藏
      editCateDialogVisible: false,
      //添加分类的表单数据对象
      addCateForm: {
        cat_name: '',
        cat_id: 0,
        cat_level: 0,
      },
      //校验规则
      addCateFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', tigger: 'blur' },
        ],
      },
      //父级数据列表
      parentCateList: [],
      //指定级联选择题的配置对象
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      //选中的父级分类的ID数组
      selectedKeys: [],
      //添加分类的表单数据
      editCateRoleForm: [],
      //修改表单的验证规则对象
      editCateRoleFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', tigger: 'blur' },
        ],
      },
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.querInfo,
      })

      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败！')
      }
      //把数据列表赋值给cateList
      this.catelist = res.data.result
      //为总数据条数赋值
      this.total = res.data.total
    },
    //监听pagesize改变事件
    handleSizeChange(newSize) {
      this.querInfo.pagesize = newSize
      this.getCateList()
    },
    //监听pagenum改变
    handleCurrentChange(newPage) {
      this.querInfo.pagenum = newPage
      this.getCateList()
    },
    //点击按钮展示添加分类对话框
    showAddCateDialog() {
      //先获取列表再展示对话框
      this.getParentCateList()
      this.addCateDialogVisible = true
    },
    //获取父级分类数据列表
    async getParentCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 },
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取父级分类数据失败！')
      }
      this.parentCateList = res.data
    },
    //选择项发生变化就会触发
    parentCateChanged() {
      //   如果selectedKeys数组中的长度大于0，证明选中的父级分类
      //   反之没有选择任何父级分类
      if (this.selectedKeys.length > 0) {
        //父级分类的ID
        this.addCateForm.cat_pid =
          this.selectedKeys[this.selectedKeys.length - 1]
        //为当前分类的等级赋值
        this.addCateForm.cat_level = this.selectedKeys.length
        return
      } else {
        //父级分类的ID
        this.addCateForm.cat_pid = 0
        //为当前分类的等级赋值
        this.addCateForm.cat_level = 0
      }
    },
    //点击添加新的分类
    addCate() {
      this.$refs.addCateFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          'categories',
          this.addCateForm
        )
        if (res.meta.status !== 201) {
          return this.$message.error('添加分类失败！')
        }
        this.$message.success('添加分类成功！')
        this.getCateList()
        this.addCateDialogVisible = false
      })
    },
    //监听对话框的关闭事件重置表单数据
    addCateDialogClosed() {
      this.$refs.addCateFormRef.resetFields()
      this.selectedKeys = []
      this.addCateForm.cat_level = 0
      this.addCateForm.cat_pid = 0
    },

    //修改分类信息
    async showEditDialog(val) {
      const { data: res } = await this.$http.get('categories/' + val)
      if (res.meta.status !== 200) {
        return this.$message.error('查询分类信息失败')
      }
      this.editCateRoleForm = res.data
      this.editCateDialogVisible = true
    },
    //监听修改用户对话框的关闭事件
    editCateDialogClosed() {
      this.$refs.editCateRoleFormRef.resetFields()
    },
    //修改用户信息并且提交进行预验证
    editCate() {
      this.$refs.editCateRoleFormRef.validate(async (valid) => {
        if (!valid) return
        console.log('editCateRoleForm', this.editCateRoleForm)
        const { data: res } = await this.$http.put(
          'categories/' + this.editCateRoleForm.cat_id,
          {
            cat_name: this.editCateRoleForm,
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('更新分类信息失败!')
        }
        //提示用户
        this.$message.success('更新分类信息成功!')
        //刷新列表
        this.getCateList()
      })
      //关闭对话框
      this.editCateDialogVisible = false
    },
    //删除分类
    async removeCateByID(cateId) {
      //弹框提示用户是否要删除
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',  
        }
      ).catch((error) => {
        return error
      })
      //如果用户确认删除返回值为字符串 confirm,用户取消则返回字符串 cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      const { data: res } = await this.$http.delete(`categories/${cateId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除分类失败！')
      }
      this.getCateList()
      this.$message.success('删除分类成功！')
    },
  },
}
</script>

<style>
.treeTable {
  margin-top: 20px;
}
.el-cascader {
  width: 100%;
}
</style>